package com.zyz.I_多线程.线程安全问题.练习;

/**
 * @author: vick
 * @Date: 2025/3/22
 * @Description:
 * @version: 1.0
 */
public class SafeBankAccount {
    private double balance;

    public SafeBankAccount(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    //存钱
    public void deposit(double amonut) {
        synchronized (this) {  //锁的是当前对象
            this.balance += amonut;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    //取钱
    public synchronized void withDraw(double amonut) { //锁的是当前对象
        if (balance >= amonut) {
            this.balance -= amonut;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
